﻿using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Dialect;
using NHibernate.Mapping.ByCode;
using FinancePortal.Domain.Model;
using System.IO;
using System;

namespace FinancePortal.Business.Infraestructure
{
    public class NHibernateHelper
    {
        private ISessionFactory _sessionFactory;

        public ISessionFactory SessionFactory
        {
            get { return _sessionFactory ?? (_sessionFactory = CreateSessionFactory()); }
        }

        private ISessionFactory CreateSessionFactory()
        {
            var dbFile = Path.Combine(System.Web.HttpContext.Current.Server.MapPath(@"~/TestData"), "TestDB.db");
            var configuration = new Configuration();

            configuration.DataBaseIntegration(c =>
             {
                 c.Dialect<SQLiteDialect>();
                 c.ConnectionString = String.Format(@"Data Source={0};Version=3;", dbFile);//@"Data Source=|DataDirectory|TestDB;Version=3;";
                 c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                 //c.SchemaAction = SchemaAutoAction.Create; // Recria a estrutura do banco automaticamente.
             });

            configuration.AddMapping(GetMapping());
            return configuration.BuildSessionFactory();
        }

        private static HbmMapping GetMapping()
        {
            var mapper = new ModelMapper();
            mapper.AddMappings(typeof(Entity).Assembly.GetExportedTypes());

            return mapper.CompileMappingForAllExplicitlyAddedEntities();
        }
    }
}
